<?php
/**
 * Created by PhpStorm.
 * User: yuyj
 * Date: 16-11-10
 * Time: 上午9:39
 */

namespace common\repositories\common;


use common\entities\common\MyscrmMaintainerAccountEntity;
use common\repositories\BaseRepository;
use Yii;
use yii\helpers\ArrayHelper;

class MyscrmMaintainerAccountRepository extends BaseRepository
{
    /**
     * @param $username
     * @return MyscrmMaintainerAccountEntity
     */
    public function getMaintainerAccount($username)
    {
        return MyscrmMaintainerAccountEntity::find()->where([
            'user_code' => $username,
            'status'    => 1,
        ])
            ->one();
    }

    public function getAllBindAccounts()
    {
        return MyscrmMaintainerAccountEntity::find()->where([
            'status' => 1,
        ])
            ->orderBy('created_on DESC')
            ->all();
    }

    public function batchBindAccount($data)
    {
        $db = MyscrmMaintainerAccountEntity::getDb();
        $transaction = $db->beginTransaction();

        try {
            # 清除
            $userGuids = ArrayHelper::getColumn($data, 'userguid');

            //if ($userGuids) {
            MyscrmMaintainerAccountEntity::deleteAll([
                'NOT IN', 'user_id', $userGuids,
            ]);
            //} else {

            //}


            $sql = $params = [];
            $user = !empty(Yii::$app->user->identity->username) ? Yii::$app->user->identity->username : '';
            foreach ($data as $index => $item) {
                $sql[] = sprintf('
                    REPLACE INTO %s (`user_id`,`user_code`,`username`, `status`,`created_by`, `modified_by`) 
                    VALUES(%s, %s, %s, "%s", "%s", "%s");',
                    MyscrmMaintainerAccountEntity::tableName(),
                    ':user_id_' . $index,
                    ':user_code_' . $index,
                    ':user_name_' . $index,
                    1,
                    $user,
                    $user
                );

                $params[':user_id_' . $index] = $item['userguid'];
                $params[':user_code_' . $index] = $item['usercode'];
                $params[':user_name_' . $index] = $item['username'];
            }

            //print_r($sql);
            //print_r($params);
           // exit;

            $sqls = implode('', $sql);
            if ($sqls && $db->createCommand($sqls, $params)->execute() === false) {
                return self::setAndReturn(__LINE__, '批量插入账号失败' . $sqls);
            }

            $transaction->commit();

            return true;
        } catch (\Exception $e) {
            $transaction->rollBack();
            print_r($e->getMessage());

            return false;
        }
    }

    public function cleanAllAccounts()
    {
        return MyscrmMaintainerAccountEntity::deleteAll();
    }
}